package tianrun.ziguan.api.calculate.config.config.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import tianrun.ziguan.api.calculate.config.constant.StringPools;
import tianrun.ziguan.api.calculate.config.utils.HttpResponseTools;
import tianrun.ziguan.api.common.core.base.ReturnMessage;

import javax.servlet.http.HttpServletRequest;

@RestControllerAdvice
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class MyGlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(MyGlobalExceptionHandler.class);

    @ExceptionHandler(value = CodeException.class)
    public ResponseEntity<ReturnMessage> codeException(CodeException e, HttpServletRequest request) {
        ReturnMessage returnMessage = new ReturnMessage();
        returnMessage.setMessage(e.getErrorCode().getDescription());
        returnMessage.setStatusCode(e.getErrorCode().getCode());
        returnMessage.setResult(StringPools.DEFAULT_MESSAGE_ERROR);
        log.info("CodeException 接口: {}, 异常信息: {}:", request.getRequestURL(), e);
        return new ResponseEntity<>(returnMessage, HttpStatus.OK);
    }
    @ExceptionHandler(value = IllegalArgumentException.class)
    public ResponseEntity<ReturnMessage> illegalArgumentException(IllegalArgumentException e, HttpServletRequest request) {
        ReturnMessage returnMessage = new ReturnMessage();
        returnMessage.setMessage(e.getMessage());
        returnMessage.setStatusCode("4001");
        returnMessage.setResult(StringPools.DEFAULT_MESSAGE_ERROR);
        log.info("IllegalArgumentException 接口: {}, 异常信息: {}:", request.getRequestURL(), e);
        return new ResponseEntity<>(returnMessage, HttpStatus.OK);
    }

    @ExceptionHandler(value = RuntimeException.class)
    public ResponseEntity<ReturnMessage> runtimeException(RuntimeException e, HttpServletRequest request) {
        ReturnMessage returnMessage = new ReturnMessage();
        returnMessage.setMessage(e.getMessage());
        returnMessage.setStatusCode(CommonErrorCode.PARAM_MISTAKE.getCode());
        returnMessage.setResult(StringPools.DEFAULT_MESSAGE_ERROR);
        log.info("RuntimeException 接口: {}, 异常信息: {}:", request.getRequestURL(), e);
        return new ResponseEntity<>(returnMessage, HttpStatus.OK);
    }

    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<ReturnMessage> exception(Exception e) {
        log.error(e.getMessage(), e);
        return HttpResponseTools.bad(e, CommonErrorCode.SYS_ERROR);
    }

}
